using System;
using System.IO;

using System.Windows.Media.DirectShow.Ogg;

namespace System.Windows.Media.DirectShow.Vorbis
{

    public interface IBitStream
    {
        bool ReadBit();
        int ReadInt32(uint bits);
        long ReadInt64(uint bits);
    }

    public class ByteArrayBitStream : IBitStream
    {

        private byte[] source;
        private int byteIndex = 0, bitIndex = 0;

        public ByteArrayBitStream(byte[] source)
        {
            this.source = source;
        }

        public bool ReadBit()
        {
            if (bitIndex > 7)
            {
                bitIndex = 0;
                byteIndex++;
                if (byteIndex >= source.Length)
                {
                    throw new EndOfStreamException();
                }
            }
            return (source[byteIndex] & (1 << (bitIndex++))) != 0;
        }

        public int ReadInt32(uint bits)
        {
            if (bits > 32)
            {
                throw new ArgumentException();
            }
            int res = 0;
            for (byte i = 0; i < bits; i++)
            {
                if (ReadBit())
                {
                    res |= 1 << i;
                }
            }
            return res;
        }

        public long ReadInt64(uint bits)
        {
            if (bits > 64)
            {
                throw new ArgumentException();
            }

            long res = 0;
            for (byte i = 0; i < bits; i++)
            {
                if (ReadBit())
                {
                    res |= 1L << i;
                }
            }
            return res;
        }
    }

}